using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NPOI.HPSF;
using Publicuse.Autofac;
using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Interface.Extend;
using Publicuse.Util;
using Publicuse.WebCore.SwaggerExtend;
using SharpCompress.Common;

namespace Geekeradmin.Controllers
{
    /// <summary>
    /// 权限控制基类
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    public class BaseController : Controller
    {
        public readonly ServiceContainer container;

        public readonly IWebHostEnvironment webHost;

        public readonly IMySqlSugarService mySqlSugar;

        public readonly IAutofaceInstance autoface;

        public readonly IOptions<DBConnectionOption> options;

        public readonly IBaseServiceExt baseServiceExt;

        public BaseController(
            IAutofaceInstance autoface,
            IMySqlSugarService mySqlSugar,
            IWebHostEnvironment webHost,
            IOptions<DBConnectionOption> options,
            IBaseServiceExt baseServiceExt
        )
        {
            container = new ServiceContainer(autoface, mySqlSugar, webHost, baseServiceExt);
            this.webHost = webHost;
            this.autoface = autoface;
            this.mySqlSugar = mySqlSugar;
            this.options = options;
            this.baseServiceExt = baseServiceExt;
        }

        /// <summary>
        /// 检查是否有新增数据的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckAdd")]
        public async Task<JsonResult> CheckAdd()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有删除数据的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckDelete")]
        public async Task<JsonResult> CheckDelete()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有修改数据的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckUpdate")]
        public async Task<JsonResult> CheckUpdate()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有导出数据的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckGetList")]
        public async Task<JsonResult> CheckGetList()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有导入数据的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckImport")]
        public async Task<JsonResult> CheckImport()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有导出数据的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckExport")]
        public async Task<JsonResult> CheckExport()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.export,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有下载导入模板的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckDown")]
        public async Task<JsonResult> CheckDown()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有上传文件的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckUpload")]
        public async Task<JsonResult> CheckUpload()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有审核的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckAudit")]
        public async Task<JsonResult> CheckAudit()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有绑定角色资源的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckRoleResource")]
        public async Task<JsonResult> CheckRoleResource()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有绑定企业的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckCompany")]
        public async Task<JsonResult> CheckCompany()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有绑定部门的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckDepartment")]
        public async Task<JsonResult> CheckDepartment()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有绑定学校的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckSchool")]
        public async Task<JsonResult> CheckSchool()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 检查是否有回收站的权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("CheckRecyclebin")]
        public async Task<JsonResult> CheckRecyclebin()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult()
                {
                    code = (int)CodeResult.success,
                    count = 1,
                    data = null
                };
                return new JsonResult(result);
            });
        }

        /// <summary>
        /// 导出数据设置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="webHost"></param>
        /// <param name="mySqlSugar"></param>
        /// <param name="query"></param>
        /// <param name="filepath"></param>
        /// <param name="exportname"></param>
        /// <param name="func"></param>
        /// <param name="queryextend"></param>
        /// <param name="tableNameys"></param>
        /// <param name="sortFile"></param>
        /// <param name="sortType"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("InitExportData"), AllowAnonymous]
        public async Task<IActionResult> InitExportData<T>(
            IWebHostEnvironment webHost,
            IMySqlSugarService mySqlSugar,
            T query,
            string filepath,
            string exportname,
            Func<string, string, List<T>, MemoryStream> func,
            Func<string, string> queryextend = null,
            string tableNameys = "",
            string sortFile = "",
            string sortType = "",
            int pageSize = 0
        )
            where T : class, new()
        {
            return await Task.Factory.StartNew<IActionResult>(() =>
            {
                var tableName = TableAtributeUtil.GetTable<T>();
                string msg = string.Empty;
                string sql = query.GetQueryString(ysql =>
                {
                    ysql = ysql.Replace(" and status =8 ", " and status<>-9 ");
                    if (queryextend != null)
                    {
                        return ysql += queryextend.Invoke(ysql);
                    }
                    else
                    {
                        return ysql;
                    }
                });
                if (!string.IsNullOrEmpty(tableNameys))
                {
                    tableName = tableNameys;
                }
                if (sortFile.IsNull())
                {
                    sortFile = "Id";
                }
                if (sortType.IsNull())
                {
                    sortType = "desc";
                }
                if (pageSize <= 0)
                {
                    pageSize = 10000000;
                }
                CommonQuery commonQuery = new CommonQuery()
                {
                    tableName = tableName,
                    sqlWhere = sql,
                    sortFile = sortFile,
                    sortType = sortType,
                    files = "*",
                    pageIndex = 1,
                    pageSize = pageSize,
                };
                List<T> list = new List<T>();
                long total = 0;
                mySqlSugar.GetList(commonQuery, out msg, out list, out total);
                CommonResult result = new CommonResult();
                string webRootPath = webHost.WebRootPath;
                string fileName = webRootPath + filepath;
                MemoryStream ms = func.Invoke(fileName, exportname, list);
                if (string.IsNullOrEmpty(msg) && list.Count > 0 && ms != null)
                {
                    result.code = (int)CodeResult.success;
                    return File(ms.ToArray(), "application/ms-excel", exportname + ".xls");
                }
                else
                {
                    return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
                }
                //else
                //{
                //    throw new Exception(msg);
                //}
            });
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="files"></param>
        /// <param name="name"></param>
        /// <param name="filename"></param>
        /// <param name="model"></param>
        /// <param name="path"></param>
        /// <param name="businessType"></param>
        /// <param name="isimag"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet("UploadFile"), AllowAnonymous]
        public async Task<CommonResult> UploadFile<T>(
            IFormFileCollection files,
            string name,
            string filename,
            UploadYPhoto model,
            string path,
            BusinessType businessType,
            bool isimag = false
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                autoface.DoWork(
                    businessType,
                    BusinessActionType.uploadfile,
                    model.logincode,
                    name,
                    BusinessLogType.writeLogToDataBase,
                    (o) =>
                    {
                        var checkisimg = true;
                        var userTable = TableAtributeUtil.GetTable<T>();
                        string msg = string.Empty;
                        string filePath = string.Empty;
                        var preff = "/Files/Uploads/" + DateTime.Now.ToString("yyyyMMdd");
                        long size = 0;
                        string FileName = string.Empty;

                        if (files == null || files.Count == 0)
                        {
                            throw new Exception("请先选择对应文件上传！");
                        }
                        foreach (var file in files)
                        {
                            if (file == null || file.Length == 0)
                            {
                                throw new Exception("请先选择对应文件上传！");
                            }

                            FileName = file.FileName;
                            var fileext = Path.GetExtension(file.FileName);
                            if (
                                fileext.Contains(".php")
                                || fileext.Contains(".asp")
                                || fileext.Contains(".jsp")
                            )
                            {
                                throw new Exception("当前文件不在允许上传范围内已拦截！");
                            }
                            var nowtime = DateTime.Now.ToString("yyyyMMddHHmmss");
                            //使用新名字命名文件
                            FileName = string.Format("{0}({2}){1}", model.uid, fileext, nowtime);
                            var fileDir = Path.Combine(path + "\\" + preff);
                            fileDir = fileDir.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                            if (!Directory.Exists(fileDir))
                            {
                                Directory.CreateDirectory(fileDir);
                            }
                            filePath = fileDir + $@"\{FileName}";
                            size += file.Length;
                            filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                            using (FileStream fs = System.IO.File.Create(filePath))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            if (
                                ImageUtil.IsImage(filePath)
                                && ImageUtil.IsImageByImageSharp(filePath)
                            ) //如果是图片进行压缩
                            {
                                checkisimg = true;
                                ImageUtil.Compressc(filePath, filePath);
                            }
                            else
                            {
                                checkisimg = false;
                            }
                        }

                        if (isimag && !checkisimg)
                        {
                            FileUtil.DelFile(filePath);
                            throw new Exception("当前文件不在允许上传范围内已拦截！");
                        }

                        List<string> msgs = new List<string>();
                        if (string.Compare(model.uid, "0", true) != 0)
                        {
                            var sqlb = $"select {filename} from {userTable} where Id={model.uid};";
                            var dt = mySqlSugar.GetDataTable(sqlb, null, out msg);
                            if (dt.Rows.Count > 0)
                            {
                                var uploadyhead = dt.Rows[0][filename].ToString();
                                if (!string.IsNullOrEmpty(uploadyhead))
                                {
                                    FileUtil.DelFile(path + filename);
                                }
                            }
                        }
                        filePath = preff + "/" + FileName;
                        if (string.Compare(model.uid, "0", true) != 0)
                        {
                            var sql =
                                $"update {userTable} set {filename}='{filePath}' where Id='{model.uid}';";
                            mySqlSugar.ExecuteSql(sql, null, out msg);
                        }
                        result.code = (int)CodeResult.success;
                        result.data = filePath;
                        if (msgs.Count > 0)
                        {
                            result.msg = string.Join(",", msgs);
                        }
                        return result;
                    },
                    null,
                    ref result
                );
                return result;
            });
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="files"></param>
        /// <param name="path"></param>
        /// <param name="module"></param>
        /// <param name="method"></param>
        /// <param name="businessType"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<CommonResult> UploadPicture(
            IFormFileCollection files,
            string path,
            string module,
            string method,
            BusinessType businessType
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                string filePath = string.Empty;
                autoface.DoWork(
                    businessType,
                    BusinessActionType.uploadfile,
                    LoginCode,
                    method,
                    BusinessLogType.writeLogToDataBase,
                    (o) =>
                    {
                        var preff =
                            "/Files/Uploads/" + module + "/" + DateTime.Now.ToString("yyyyMMdd");
                        long size = 0;
                        string FileName = string.Empty;
                        foreach (var file in files)
                        {
                            FileName = file.FileName;
                            var fileext = Path.GetExtension(file.FileName);
                            if (
                                fileext.Contains(".php")
                                || fileext.Contains(".asp")
                                || fileext.Contains(".jsp")
                            )
                            {
                                throw new Exception("当前文件不在允许上传范围内已拦截！");
                            }
                            var fileDir = Path.Combine(path + "\\" + preff);
                            fileDir = fileDir.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                            if (!Directory.Exists(fileDir))
                            {
                                Directory.CreateDirectory(fileDir);
                            }
                            var filePath = fileDir + $@"\{FileName}";
                            size += file.Length;
                            filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                            using (FileStream fs = System.IO.File.Create(filePath))
                            {
                                file.CopyTo(fs);
                                fs.Flush();
                            }
                            if (ImageUtil.IsImage(filePath)) //如果是图片进行压缩
                            {
                                ImageUtil.Compressc(filePath, filePath);
                            }
                        }
                        filePath = preff + "/" + FileName;
                        result.code = (int)CodeResult.success;
                        result.data = filePath;
                        return result;
                    },
                    null,
                    ref result
                );
                return result;
            });
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [HttpGet("DownFile"), AllowAnonymous]
        public async Task<IActionResult> DownFile(string path)
        {
            return await Task.Factory.StartNew<IActionResult>(() =>
            {
                path = EnDecryptionUtil.DESDecryptbyqd(path);
                string newpath = string.Empty;
                string contenttype = string.Empty;
                try
                {
                    //获取文件后缀名
                    var filenameext = Path.GetExtension(path);
                    //获取文件名称
                    var filename = Path.GetFileNameWithoutExtension(path);
                    contenttype = filenameext.GetFileTypeb();
                    path = "wwwroot" + path.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                    var msb = System.IO.File.OpenRead(path);
                    return File(msb, contenttype, filename + filenameext);
                }
                catch (Exception ex)
                {
                    Log log = new Log()
                    {
                        lmodule = "下载文件",
                        ltype = path,
                        luser = "系统",
                        lsuccess = 2,
                        status = 1,
                        lcontent = contenttype + "|" + newpath + "|" + ex.Message
                    };
                    mySqlSugar.Insert(log, out var msg);
                    return null;
                }
            });
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [HttpGet("DownFileb"), AllowAnonymous]
        //[RequestSizeLimit(2004857600)]
        public async Task<IActionResult> DownFileb(string path)
        {
            return await Task.Factory.StartNew<IActionResult>(() =>
            {
                string newpath = string.Empty;
                string contenttype = string.Empty;
                try
                {
                    //获取文件后缀名
                    var filenameext = Path.GetExtension(path);
                    //获取文件名称
                    var filename = Path.GetFileNameWithoutExtension(path);
                    contenttype = filenameext.GetFileTypeb();
                    path = "wwwroot" + path.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                    var msb = System.IO.File.OpenRead(path);
                    return File(msb, contenttype, filename + filenameext);
                }
                catch (Exception ex)
                {
                    Log log = new Log()
                    {
                        lmodule = "下载文件",
                        ltype = path,
                        luser = "系统",
                        lsuccess = 2,
                        status = 1,
                        lcontent = contenttype + "|" + newpath + "|" + ex.Message
                    };
                    mySqlSugar.Insert(log, out var msg);
                    return null;
                }
            });
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("Downtaskfile"), AllowAnonymous]
        public async Task<IActionResult> Downtaskfile(string Id)
        {
            return await Task.Factory.StartNew<IActionResult>(() =>
            {
                var path = string.Empty;
                var table = TableAtributeUtil.GetTable<Downtask>();
                var sql = $"select * from {table} where Id='{Id}';";
                var list = this.mySqlSugar.Query<Downtask>(sql, null, out var msg);
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    var curdata = list.FirstOrDefault();
                    path = curdata.furl;
                    path = EnDecryptionUtil.DESDecryptbyqd(path);
                    string newpath = string.Empty;
                    string contenttype = string.Empty;
                    try
                    {
                        curdata.fdowncount = curdata.fdowncount + 1;
                        if (string.IsNullOrEmpty(curdata.fdowntime))
                        {
                            curdata.fdowntime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        else
                        {
                            curdata.fdowntime =
                                curdata.fdowntime
                                + "|"
                                + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        var fdownucode = HttpContextExtendBase.GetLoginCode();
                        if (string.IsNullOrEmpty(curdata.fdownucode))
                        {
                            curdata.fdownucode = fdownucode;
                        }
                        else
                        {
                            curdata.fdownucode = curdata.fdownucode + "|" + fdownucode;
                        }
                        this.mySqlSugar.Update<Downtask>(curdata, out msg);
                        //获取文件后缀名
                        var filenameext = Path.GetExtension(path);
                        //获取文件名称
                        var filename = Path.GetFileNameWithoutExtension(path);
                        contenttype = filenameext.GetFileTypeb();
                        path = this.webHost.WebRootPath + path;
                        path = path.Replace("\\", "/"); // Linux系统部署路径需要改成这样
                        if (FileUtil.Exists(path))
                        {
                            var msb = System.IO.File.OpenRead(path);
                            return File(msb, contenttype, filename + filenameext);
                        }
                        else
                        {
                            byte[] buffer = new byte[0];
                            return File(buffer, contenttype, filename + filenameext);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log log = new Log()
                        {
                            lmodule = "下载文件",
                            ltype = path,
                            luser = "系统",
                            lsuccess = 2,
                            status = 1,
                            lcontent = contenttype + "|" + newpath + "|" + ex.Message
                        };
                        mySqlSugar.Insert(log, out msg);
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            });
        }

        /// <summary>
        /// 删除指定附件信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Id"></param>
        /// <param name="filename"></param>
        /// <param name="filepath"></param>
        /// <param name="businessType"></param>
        /// <returns></returns>
        public async Task<CommonResult> DeleteFile<T>(
            string Id,
            string filename,
            string filepath,
            BusinessType businessType
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                autoface.DoWork(
                    businessType,
                    BusinessActionType.deletefile,
                    LoginCode,
                    Id + "|" + filename,
                    BusinessLogType.writeLogToDataBase,
                    (o) =>
                    {
                        var userTable = TableAtributeUtil.GetTable<T>();
                        string msg = string.Empty;
                        var sqlb = $"select {filename} from {userTable} where Id='{Id}';";
                        var dt = mySqlSugar.GetDataTable(sqlb, null, out msg);
                        if (string.IsNullOrEmpty(msg) && dt != null && dt.Rows.Count > 0)
                        {
                            var filesrc = dt.Rows[0][filename].ToString();
                            if (!string.IsNullOrEmpty(filesrc))
                            {
                                var filesrclist = filesrc.Split(',');
                                List<string> newfilesrclist = new List<string>();
                                foreach (var item in filesrclist)
                                {
                                    if (string.Compare(item, filepath, true) != 0)
                                    {
                                        newfilesrclist.Add(item);
                                    }
                                }
                                var newfilesrc = string.Join(",", newfilesrclist);
                                sqlb =
                                    $"update {userTable} set {filename} ='{newfilesrc}' where Id='{Id}'; ";
                                mySqlSugar.ExecuteSql(sqlb, null, out msg);
                                var path = this.webHost.WebRootPath + filepath;
                                if (FileUtil.Exists(path))
                                {
                                    FileUtil.DelFile(path);
                                }
                                sqlb = $"select {filename} from {userTable} where Id='{Id}';";
                                dt = mySqlSugar.GetDataTable(sqlb, null, out msg);
                                {
                                    if (
                                        string.IsNullOrEmpty(msg)
                                        && dt != null
                                        && dt.Rows.Count > 0
                                    )
                                    {
                                        filesrc = dt.Rows[0][filename].ToString();
                                        result.data = filesrc;
                                        if (!string.IsNullOrEmpty(filesrc))
                                        {
                                            result.count = filesrc.Split(',').Length;
                                        }
                                        else
                                        {
                                            result.count = 0;
                                        }
                                    }
                                }
                            }
                        }
                        return result;
                    },
                    null,
                    ref result
                );
                return result;
            });
        }
    }
}
